import { useRef } from 'react';
import { atom, useRecoilState } from 'recoil';

/** 每个渲染表格存储的全局数据 */
interface ITableState {
    /** 聚焦的表格项 */
    focusCell: [number, number];
    /** 聚焦表格项是否正在编辑 */
    cellIsEditing: boolean;
    /** 表格id */
    tableId?: string;
}

export const hopetoTableState = atom<ITableState>({
    key: 'hopetoTable',
    default: {
        focusCell: [-1, -1],
        cellIsEditing: false,
        tableId: ''
    }
});

/** 获取某个表格的全局数据 */
export function useTableState(tableId: string) {
    const [data, setData] = useRecoilState(hopetoTableState);
    const dataRef = useRef(data);
    dataRef.current = data;

    /** 更新聚焦表格项 */
    const setFocusCell = (focusCell: [number, number]) => {
        setData((prev) => {
            return Object.assign({}, prev, {
                tableId,
                focusCell
            });
        });
    }

    /** 更新是否正在编辑状态 */
    const setCellIsEditing = (cellIsEditing: boolean) => {
        setData((prev) => {
            return Object.assign({}, prev, {
                tableId,
                cellIsEditing
            });
        });
    }
    return {
        data,
        dataRef,
        setCellIsEditing,
        setFocusCell
    };
}